package com.atguigu.lease.web.app.service.impl;



import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.redis.RedisConstant;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private Client client;
    @Autowired
    private UserInfoService userInfoService;
    @Override
    public void sendCode(String phone) throws Exception {
        if (StringUtils.isBlank(phone)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        String key= RedisConstant.APP_LOGIN_PREFIX+phone;
        if (Boolean.TRUE.equals(redisTemplate.hasKey(key))){
            throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
        }
        Random random=new Random();
        StringBuilder builder=new StringBuilder();
        for (int i = 0; i < 6; i++) {
            builder.append(random.nextInt(10));
        }
        SendSmsRequest sendSmsRequest=new SendSmsRequest();
        sendSmsRequest.setPhoneNumbers(phone);
        sendSmsRequest.setSignName("阿里云短信测试");
        sendSmsRequest.setTemplateCode("SMS_154950909");
        sendSmsRequest.setTemplateParam("{\"code\":\"" + builder + "\"}\n");
        redisTemplate.opsForValue().set(key,builder,RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC, TimeUnit.SECONDS);
        client.sendSms(sendSmsRequest);
    }

    @Override
    public String login(LoginVo loginVo) {
        if (StringUtils.isBlank(loginVo.getPhone())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        String key=RedisConstant.APP_LOGIN_PREFIX+loginVo.getPhone();
        if (StringUtils.isBlank(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }else if (!redisTemplate.hasKey(key)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }else if (!loginVo.getCode().equals(redisTemplate.opsForValue().get(key))){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        LambdaQueryWrapper<UserInfo> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getPhone,loginVo.getPhone());
        UserInfo userInfo = userInfoService.getOne(wrapper);
        String token;
        if (userInfo!=null&&userInfo.getStatus().equals(BaseStatus.DISABLE)){
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }else if (userInfo!=null&&userInfo.getStatus().equals(BaseStatus.ENABLE)){
            token=JwtUtil.createToken(userInfo.getId(),userInfo.getPhone());
        }else {
            UserInfo user=new UserInfo();
            user.setPhone(loginVo.getPhone());
            user.setStatus(BaseStatus.ENABLE);
            user.setNickname("用户-"+ UUID.randomUUID().toString().substring(0,6));
            userInfoService.save(user);
            token = JwtUtil.createToken(user.getId(), loginVo.getPhone());
        }
        return token;
    }

    @Override
    public UserInfoVo getUser(Long userId) {
        UserInfo info = userInfoService.getById(userId);
        return new UserInfoVo(info.getNickname(),info.getAvatarUrl());
    }
}
